/**
 * @ActorProxyer.as
 *
 * @author sodaChen mail:sujun10#21cn.com
 * @version 1.0
 * <br>Copyright (C), 2013 asFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:ASFrame
 * <br>Date:2016-6-11
 */
package com.asframe.action
{
	import com.asframe.collections.maps.HashMap;

	import flash.utils.Dictionary;

	/**
	 * 表演代理者，支持aciton的队列、并发、同名排斥模式
	 * @author sodaChen
	 * Date:2016-6-11
	 */
	public class ActorProxyer
	{
		/** 表演者 **/
		private var _actor:IActor;
		/** 动作集合 **/
		private var _actionMap:HashMap;
		/** 存放并发的id引用 **/
		private var _sameIdMap:HashMap;
		/** 并发id增长值 **/
		private var _sameIdCount:int;
		private var _actionDic:Dictionary;

		public function ActorProxyer(actor:IActor)
		{
			this._actor = actor;
			_actionMap = new HashMap();
			_actionDic = _actionMap.getContainer();
			_sameIdMap = new HashMap();
		}
		public function setActor(actor:IActor):void
		{
			this._actor = actor;
		}

		public function act(action:IAction,callBack:Function = null,param:* = null):Boolean
		{
			if(callBack != null || param != null)
			{
				action.initAction(callBack,param);
			}

			//查看是否有同名的,目前先不处理队列，只处理单独，并列以及替换3种情况
			var act:IAction = _actionMap.get(action.getName());
			if(action.getType() == ActionConsts.QUEUE)
			{
				var queueProxy:QueueActionProxy = null;
				if(act == null)
				{
					//创建一个新的队列Action代理
					queueProxy = new QueueActionProxy();
					_actionMap.put(action.getName(),queueProxy);
					queueProxy.addAction(action);
					queueProxy.start(_actor);
				}
				else
				{
					queueProxy = QueueActionProxy(act);
					queueProxy.addAction(action);
				}
				return true;
			}
			if(act != null)
			{
				//查看是否是独占，已经存在，就不可代替
				if(action.getType() == ActionConsts.ALONE)
				{
					//直接删除老的
					delAction(act);
				}
				else
				{
					//处理并发情况，生成新的索引作为name
					_sameIdCount++;
					_sameIdMap.put(action,action.getName() + _sameIdCount);
					_actionMap.put(action.getName() + _sameIdCount,action);
				}
			}
			else
			{
				//单独排斥和第一次并发就直接添加
				_actionMap.put(action.getName(),action);
			}
			action.start(_actor);
			return true;
		}

		public function delAction(action:IAction,isDestory:Boolean = true):void
		{
				//如果action是队列，并且不是队列代理本身销毁
			if(action.getType() == ActionConsts.QUEUE && action != QueueActionProxy)
			{
				QueueActionProxy(action).actAction();
				return ;
			}
			//并发类型，并且是存放了并发索引新生成key的对象
			if(action.getType() == ActionConsts.SAME && _sameIdMap.hasKey(action))
			{
				_actionMap.remove(_sameIdMap.get(action));
			}
			else
			{
				_actionMap.remove(action.getName());
			}
			//执行销毁)
			if(isDestory)
				action.destroy();
		}
	}
}